/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request/blob/HEAD/README_zh-CN.md
 */
import { extend } from 'umi-request';
import { notification, Modal } from 'antd';
import axios from './axios.min';
import { Auth } from './MFAuth';
import apiPath from '@/configs/api.map';
import { defaultHeaders } from '@/configs';

const { api_checkMFA: checkMFA_URL, api_refreshToken: refreshToken_URL } = apiPath;

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '当前角色没有访问此接口的权限',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  413: '需要账号密码验证',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。'
};

const output = (...args) => {
  // eslint-disable-next-line no-console
  console.log(...args);
};

/**
 * 异常处理程序
 */
const errorHandler = error => {
  const { response } = error;
  output('%c RequestError:', 'color:red', error);
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText
    });
  }
};

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  errorHandler, // 默认错误处理
  credentials: 'include' // 默认请求是否带上cookie
});

const $request = async (url, options) => {
  const flag = await Auth.validate({ url, authCheck });
  if (!flag) {
    output('%c AuthCode:', 'color:red', flag);
    return Promise.resolve({ code: '999999', message: '已取消MFA验证' });
  }
  const response = request(url, options);
  output(`%c ${(options && options.method) || 'GET'}:`, 'color:green', url);
  return response;
};

const reqState = {
  cacheReq: [],
  cacheToken: null,
  refreshStatus: false,
  get token() {
    if (this.cacheToken) return this.cacheToken;
    const tokenInfo = localStorage.getItem('token');
    let tokenObj = {};
    try {
      tokenObj = JSON.parse(tokenInfo) || {};
    } catch (error) {
      return {};
    }
    return tokenObj;
  },
  set token(tokenObj) {
    this.cacheToken = tokenObj;
    if (!tokenObj) {
      localStorage.removeItem('token');
    } else {
      localStorage.setItem('token', JSON.stringify(tokenObj));
    }
  }
};

axios.interceptors.request.use(
  config => {
    const { accessToken: Authorization } = reqState.token;
    return {
      ...config,
      headers: {
        ...config.headers,
        Authorization
      }
    };
  },
  error => Promise.reject(error)
);

axios.interceptors.response.use(
  async response => {
    let res = response.data || {};
    const { code } = res;
    if (code === 402) {
      await sendRefreshToken();
      const { data = '{}', method, url } = response.config;
      const $data = JSON.parse(data);
      res = await axios({ url, method, data: $data });
    } else if (code === 403) {
      toLoginPage();
    }
    return res;
  },
  error => Promise.reject(error)
);

class RequestCache {
  constructor(url, options) {
    this.url = url;
    this.options = options;
    const This = this;
    this.Promise = new Promise((resolve, reject) => {
      This.resolveBack = resolve;
      This.rejectBack = reject;
    });
  }

  dispatch() {
    const { accessToken } = reqState.token;
    const { url, options, resolveBack, rejectBack } = this;
    $request(url, { ...options, Authorization: accessToken })
      .then(res => {
        resolveBack(res);
      })
      .catch(err => {
        rejectBack(err);
      });
  }

  deffer() {
    return this.Promise;
  }
}

function toLoginPage() {
  reqState.token = null;
  setTimeout(() => {
    const { href, origin, pathname } = window.location;
    const params = href.split('redirect=');
    const redirect = decodeURIComponent(params.length === 1 ? params[0] : params[params.length - 1]);
    const codeRedirect = encodeURIComponent(redirect);
    window.location.replace(`${origin + pathname}#/user/login?redirect=${codeRedirect}`);
  }, 0);
}

function authToast(url) {
  Modal.warning({
    title: '权限验证',
    content: `请联系管理员，你没有权限访问此接口数据：${url}`
  });
}

async function sendRefreshToken() {
  reqState.refreshStatus = true;
  const { token, cacheReq } = reqState;
  const { refreshToken } = token;
  const options = {
    method: 'post',
    url: refreshToken_URL,
    data: { refreshToken }
  };
  const res = await axios(options);
  const { code, data } = res;
  output('refreshToken:', code);
  if (code !== '000000') {
    toLoginPage();
  } else {
    reqState.token = { ...token, ...data };
    while (cacheReq.length > 0) {
      cacheReq.shift().dispatch();
    }
  }
  reqState.refreshStatus = false;
  return true;
}

async function authCheck(url, authcode) {
  const { userId } = reqState.token;
  const options = {
    method: 'POST',
    url: checkMFA_URL,
    data: { userId, url, authcode }
  };
  const res = await axios(options);
  return res;
}

function cacheRequest(url, options) {
  const req = new RequestCache(url, options);
  reqState.cacheReq.push(req);
  if (!reqState.refreshStatus) {
    sendRefreshToken();
  }
  return req.deffer();
}

async function requestInterceptor(url, options) {
  const { accessToken: Authorization } = reqState.token;
  const headers = { ...options.headers, ...defaultHeaders, Authorization };
  return { url, options: { ...options, headers } };
}

async function requestMiddleware(ctx, next) {
  const { req } = ctx;
  const { url, options = {} } = req;
  await next();
  try {
    const { res } = ctx;
    const response = await res.clone().json();
    const { code } = response;
    if (code === 402 || code === 'AM4002') {
      // 鉴权系统返回 code === 'AM4002'
      output('after cache:', url);
      ctx.res = await cacheRequest(url, options);
    } else if (code === 403 || code === 'AM4001') {
      // 鉴权系统返回 code === 'AM4001'
      toLoginPage();
    } else if (code === 405) {
      authToast(url);
    } else if (code === 498) {
      Modal.warning({
        title: '二次验证',
        content: `您未通过二次验证，接口：${url}`
      });
    } else if (response.err) {
      ctx.res = response.err;
    } else if (res.status >= 400) {
      const err = {
        code: response.code || res.status,
        message: response.message || codeMessage[response.status]
      };
      ctx.res = err;
      output('%c error:', 'color:red', err);
    }
  } catch (error) {
    output('%c error:', 'color:red', error);
  }
}

function reqProxy(prefix) {
  return (url, opiotns) => $request(prefix + url, opiotns);
}

// request拦截器, 改变url 或 options.
request.interceptors.request.use(requestInterceptor);

request.use(requestMiddleware, { core: true });

export { axios, reqProxy };
export default $request;
